#include <iostream>
#include <vector>
#include "Thread.hpp"

using namespace ThreadModule;

#define NUM 4

//创建锁  加锁和解锁操作是原子的
// pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;

int ticketnum = 10000;//共享资源

class ThreadData
{
public:
    std::string name;
    pthread_mutex_t *lock_ptr;
};

void Ticket(ThreadData &td)
{
    while(true)
    {
        //加锁
        // pthread_mutex_lock(&lock);
        pthread_mutex_lock(td.lock_ptr);
        if(ticketnum > 0)
        {
            usleep(1000);
            printf("get a new ticket,who get it: %s,id: %d\n", td.name.c_str(), ticketnum--);
            
            //解锁
            // pthread_mutex_unlock(&lock);
            pthread_mutex_unlock(td.lock_ptr);
        }
        else
        {
            // pthread_mutex_unlock(&lock); //解锁
            pthread_mutex_unlock(td.lock_ptr);
            break;
        }
    }
}

int main()
{
    pthread_mutex_t lock;  //创建锁
    pthread_mutex_init(&lock, nullptr); //初始化锁

    //构建线程对象
    std::vector<Thread<ThreadData>> threads;
    for(int i = 0; i < NUM; i++)
    {
        ThreadData *td = new ThreadData();
        td->lock_ptr = &lock;
        threads.emplace_back(Ticket, *td);
        td->name = threads.back().Name();
    }

    //启动线程
    for(auto &thread : threads)
    {
        thread.Start();
    }

    //等待线程
    for(auto &thread : threads)
    {
        thread.Join();
    }

    pthread_mutex_destroy(&lock); //销毁锁

    return 0;
}
